package gae.testjig.server;

import com.google.appengine.api.memcache.Expiration;
import com.google.appengine.api.memcache.MemcacheService;
import com.google.appengine.api.memcache.MemcacheServiceFactory;

// from http://blog.listry.com/2010/05/app-engine-locking-with-memcache.html
public class MemcacheMutex {

	private String key;
	private int maxTimeout;
	private boolean locked = false;

	public MemcacheMutex(String key, int maxTimeout) {
		this.key = "mcmutex." + key;
		this.maxTimeout = maxTimeout;
	}

	public boolean TryLock() {
		if ( locked ) {
			return true;
		}
		MemcacheService mc = MemcacheServiceFactory.getMemcacheService();
		locked = mc.put(key, "not used", Expiration.byDeltaMillis(maxTimeout), MemcacheService.SetPolicy.ADD_ONLY_IF_NOT_PRESENT);
		return locked;
	}

	public void Unlock() {
		if ( locked ) {
			MemcacheServiceFactory.getMemcacheService().delete(key);
		}
		locked = false;
	}

}